package com.efun.framework.i18n;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by kinven on 17/8/16.
 */
public class GameLocaleChangeInterceptor extends HandlerInterceptorAdapter {
    private final static String DEFAULT_GAMECODE_PARAMETER = "gamecode";
    private final static Map<String,Locale> LOCALE_MAP = new ConcurrentHashMap<String,Locale>();
    private final static Map<String,Locale> GAMECODE_LOCALE = new ConcurrentHashMap<String,Locale>();

    private String paramName=DEFAULT_GAMECODE_PARAMETER;

    public void setParamName(String paramName) {
        this.paramName = paramName;
    }

    public String getParamName() {
        return paramName;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String gameCode = request.getParameter(paramName);
        if(!StringUtils.isEmpty(gameCode) && !GAMECODE_LOCALE.containsKey(gameCode)) {
            LocaleContextHolder.setLocale(localeFormGameCode(gameCode));
            GAMECODE_LOCALE.put(gameCode,localeFormGameCode(gameCode));
            LocaleContextHolder.setTimeZone(timeZonefromGameCode(gameCode));
        }
        return true;
    }

    private Locale localeFormGameCode(String gameCode) {
        String zone = gameCode.substring(0,2).toLowerCase();
        return LOCALE_MAP.get(zone);
    }

    private TimeZone timeZonefromGameCode(String gameCode) {
        return TimeZone.getDefault();
    }

    static {
        LOCALE_MAP.put("tw",Locale.TAIWAN); //港台
        LOCALE_MAP.put("hk",Locale.TAIWAN); //该台
        LOCALE_MAP.put("kr",Locale.KOREA);  //韩国

        LOCALE_MAP.put("kl",Locale.KOREA); //韩国联运
    }


}
